package crmdna.api.servlet;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.Credential;

import crmdna.common.APIResponse;
import crmdna.common.APIResponse.Status;

public final class AuthorizationFilter implements Filter {

	private FilterConfig filterConfig = null;	
	private final static Logger LOGGER = Logger.getLogger(AuthorizationFilter.class.getName());

	private Credential googleCredential;
	private AuthorizationCodeFlow googleAuthflow;

	public void init(FilterConfig filterConfig) throws ServletException {

		LOGGER.setLevel(Level.INFO);		
		LOGGER.info("Initializing Authorization Filter");
		this.filterConfig = filterConfig;
		
		try {
			this.googleAuthflow = Utils.newFlow();
		} catch (IOException e) {
			//FIXME
		}
	}

	public void destroy() {
		this.filterConfig = null;
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		
		if (filterConfig == null)
			return;
		
		LOGGER.info("Invoking Authorization Filter");
	
		HttpServletRequest request = (HttpServletRequest) req;	
		HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Access-Control-Allow-Origin", "https://ishacrmdev.appspot.com");
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Max-Age", "86400");
        
		HttpSession session = request.getSession(true);
		Object loginObj = session.getAttribute("login");
		if(loginObj == null) {
			new APIResponse().status(Status.ERROR_LOGIN_REQUIRED).setJsonResponse(response);
			LOGGER.info("login missing in session");
			return;
		}
		
		String login = loginObj.toString();		
		String loginType = session.getAttribute("loginType").toString();
		if(loginType == "google") {
			
			googleCredential = googleAuthflow.loadCredential(login);
			if (googleCredential == null || googleCredential.getAccessToken() == null) {
				new APIResponse().status(Status.ERROR_LOGIN_REQUIRED).setJsonResponse(response);
				LOGGER.info("google auth expired for " + login);
				return;
			}
		}
		else {
			
		
		}

		chain.doFilter(request, response);
	}
}